package JavaUtils.web.req.io;

import JavaUtils.CSUtils.CFile;
import JavaUtils.CSUtils.CString;
import JavaUtils.CSUtils.Log.CLog;
import JavaUtils.web.IWebCallback;
import JavaUtils.web.ReqInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;

public class Req_fileUpload {
    static final String tag = "Req_fileUpload";

    public static IWebCallback fileUpload( ) {
        IWebCallback fileUploadEvent = new IWebCallback() {
            @Override
            public void MsgHandle(ReqInfo reqInfo) throws IOException {
                String filePath = reqInfo.dataMap.get("filePath");
                int uploadType = Integer.parseInt(reqInfo.dataMap.get("uploadType"));
                if (uploadType == 1) {
                    File file = new File(filePath);
                    if (file.exists() == false) {
                        reqInfo.resp_txt = "0";
                    }
                    reqInfo.resp_txt = file.length() + "";

                    file.delete();
                    reqInfo.resp_txt = "0";
                } else if (uploadType == 2) {
                    long fileLength = Long.parseLong(reqInfo.dataMap.get("fileLength"));
                    long fileStartPos = Long.parseLong(reqInfo.dataMap.get("fileStartPos"));
                    long fileEndPos = Long.parseLong(reqInfo.dataMap.get("fileEndPos"));
                    reqInfo.resp_txt = fileEndPos + "";

                   // FormDataUtil.getData(reqInfo.dataBytesList, fileStartPos, fileEndPos);

                    File file = new File(filePath);
                    File dir = new File(file.getParent());
                    if (!dir.exists()) {
                        dir.mkdirs(); //创建目录
                    }
                    if (!file.exists()) { // 不存在
                        if (file.createNewFile()) {
                            CLog.f(tag, "创建文件成功！.....%s", filePath);
                        } else {
                            CLog.exf(tag, "文件创建失败.....%s", filePath);
                        }
                        FileOutputStream fos = new FileOutputStream(file);
                        for (byte[] bytes : reqInfo.dataBytesList) {
                            fos.write(bytes);
                        }
                        fos.flush();
                    } else {
                        // 存储在服务器中的文件长度
                        long _fileSize = file.length();
                        long _startPos = 0;
                        // 判断是否已下载完成
                        if (fileLength > _fileSize) {
                            // 断点下载
                            _startPos = _fileSize;
                        } else {
                            // 重新下载
                            file.delete();
                            file.createNewFile();
                            reqInfo.resp_txt = "0";
                            CLog.exf(tag, "删除文件重新下载....fileLength=%s......_fileSize=%s....%s", fileLength, _fileSize, filePath);
                            return;
                        }
                        if (_startPos == fileStartPos) {
                            CLog.f(tag, "数据..开始写入...._startPos=%s......fileStartPos=%s....fileEndPos=%s", _startPos, fileStartPos, fileEndPos);
                        } else {
                            CLog.exf(tag, "数据长度不相等...._startPos=%s......fileStartPos=%s....fileEndPos=%s", _startPos, fileStartPos, fileEndPos);
                        }

                        RandomAccessFile rantmpfile = new RandomAccessFile(file, "rw");
                        //java.io.InputStream.skip() 用法：跳过 n 个字节（丢弃） 如果 n
                        //为负，则不跳过任何字节。
                        //dis.skip(pointSize); （已从客户端读取进度）

                        rantmpfile.seek(_startPos);
                        for (byte[] bytes : reqInfo.dataBytesList) {
                            rantmpfile.write(bytes);
                        }
                    }
                    CLog.f(tag, "数据..写入完成.......size=%s....startPos=%s__endPos=%s....fileLen=%s", reqInfo.dataBytesList.size(), fileStartPos, fileEndPos, file.length());
                }
                //reqInfo.respState = 200;
            }
        };
        return fileUploadEvent;
    }


    static void test_002() {
        String path = "/Users/mac/Downloads/src1su.txt";
        List<byte[]> list = CFile.ReadBytesLine(path);
        test_ShowLog_ByteList(path, list);
    }

    static void test_ShowLog_ByteList(String path, List<byte[]> list) {
        int startBytesIndex = 0;
        byte[] bb1 = list.get(startBytesIndex);
        while (bb1.length == 0) {
            startBytesIndex++;
            bb1 = list.get(startBytesIndex);
        }

        CLog.i(tag, path + "...开头..........." + CString.toStringLog(bb1));
        byte[] bb2 = list.get(list.size() - 1);
        CLog.i(tag, path + "...结尾..........." + CString.toStringLog(bb2, bb2.length - 10, bb2.length - 1));

        String str1 = new String(bb1, 0, Math.min(bb1.length, 200));
        CLog.i(tag, path + "...开头mmm..........." + str1);
        int len = 200;
        int start = bb2.length - len - 1;
        if (bb2.length < len) {
            start = 0;
            len = bb2.length;
        }
        String str2 = new String(bb2, start, len);
        CLog.i(tag, path + "...结尾mmm..........." + str2);
    }
}
